<template>
  <el-dialog
    top="30px"
    width="600px"
    class="dialog-sm"
    append-to-body
    title="保费审核"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <div>
      <div class="row mb-3">
        <div class="col">
          <span>提交金额：</span>
          <span>{{ editRow.actual_warrant_fee }}万元</span>
        </div>
        <div class="col">
          <span>提交时间：</span>
          <span>{{ editRow.actual_warrant_date }}</span>
        </div>
      </div>
      <div class="d-flex mb-3">
        <span>附件信息：</span>
        <div class="flex-1">
          <img-card :images="attachs"></img-card>
        </div>
      </div>

      <hr />

      <el-form :model="ruleForm" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="到账金额" prop="confirm_warrant_fee">
          <el-input
            :min="0"
            type="number"
            v-model="ruleForm.confirm_warrant_fee"
            placeholder="到账金额"
            style="width: 260px"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="到账时间" prop="confirm_fee_time" class="form-control-ml">
          <el-date-picker
            type="date"
            class="w-100"
            value-format="yyyy-MM-dd"
            placeholder="到账时间"
            v-model="ruleForm.confirm_fee_time"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="saveLoading"
            :disabled="returnLoading"
            class="btn-long"
          >
            完成审核
          </el-button>
          <el-button
            type="warning"
            @click="handleReturn"
            :disabled="saveLoading"
            :loading="returnLoading"
            class="btn-long"
          >
            退回
          </el-button>
          <el-button class="btn-long" @click="beforeClose" :disabled="saveLoading || returnLoading">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { arrayFromString, sub } from '@vimi/utils-tool'
import { num } from '@/common/plugins/tools/format'
import { PayStatus } from '@/bigcredit/views/settle/collect/model'

import ImgCard from '@/components/ImgCard'

export default {
  components: {
    ImgCard,
  },
  props: {
    visible: Boolean,
    editRow: {
      type: Object,
      default() {
        return {}
      },
    },
    collectRow: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      tableName: 'credit_warrant_fee_register',
      saveLoading: false,
      ruleForm: {
        confirm_warrant_fee: '',
        confirm_fee_time: '',
      },
      rules: {
        confirm_warrant_fee: [
          { required: true, message: '请输入到账金额', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              value = Number(value)
              if (value <= 0) {
                return callback(new Error('金额不能小于等于0'))
              }
              callback()
            },
            trigger: 'blur',
          },
        ],
        confirm_fee_time: [{ required: true, message: '请选择到账时间', trigger: 'change' }],
      },
      returnLoading: false,
      finishedTotalFunds: 0,
    }
  },
  computed: {
    ...mapGetters(['user']),
    attachs() {
      return arrayFromString(this.editRow.attachment)
    },
    accountingFunds() {
      return num(this.collectRow.check_warranty_fee)
    },
    leftFunds() {
      return Math.max(sub(this.accountingFunds, this.finishedTotalFunds), 0)
    },
  },
  watch: {
    editRow: {
      handler: function () {
        this.initForm()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    initForm() {
      Object.keys(this.ruleForm).forEach(key => {
        this.ruleForm[key] = this.editRow[key] || ''
      })

      this.getFinishedTotalFunds()
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm(
            this.ruleForm.confirm_warrant_fee > this.leftFunds
              ? `累计到账金额（${this.finishedTotalFunds || 0}+${
                  this.ruleForm.confirm_warrant_fee || 0
                }万元）已超过累计核算金额（${this.accountingFunds || 0}万元）`
              : '确认完成审核?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: this.ruleForm.confirm_warrant_fee > this.leftFunds ? 'warning' : 'info',
            }
          )
            .then(() => {
              this.submitApply()
            })
            .catch(() => {})
        } else {
          this.$message.error('输入错误，请重新输入')
        }
      })
    },
    async submitApply() {
      const formData = {
        ...this.ruleForm,
        pay_status: 2,
      }

      try {
        this.saveLoading = true

        const id = this.editRow.id
        if (id) {
          await this.updateData(id, formData)
        } else {
          throw new Error('没有需要审核的登记信息')
        }

        this.$message.success(`审核成功`)
        this.$emit('success')
        this.beforeClose()
      } catch (error) {
        this.$message.error(`审核失败，请重试`)
      } finally {
        this.saveLoading = false
      }
    },
    handleReturn() {
      this.$confirm('确认退回该登记信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          this.submitReturn()
        })
        .catch(() => {})
    },
    async submitReturn() {
      const formData = {
        pay_status: 0,
      }

      try {
        this.returnLoading = true

        const id = this.editRow.id
        if (id) {
          await this.updateData(id, formData)
        } else {
          throw new Error('没有需要退回的登记信息')
        }

        this.$message.success(`退回成功`)
        this.$emit('success')
        this.beforeClose()
      } catch (error) {
        this.$message.error(`退回失败，请重试`)
      } finally {
        this.returnLoading = false
      }
    },
    updateData(id, data) {
      return this.$api.updateData({
        table: this.tableName,
        id,
        data,
      })
    },
    // 获取项目所有登记的总金额
    getFinishedTotalFunds() {
      const relatedId = this.collectRow.customer_related_id
      if (!relatedId) return

      this.$api
        .getData({
          table: 'credit_warrant_fee_register',
          params: {
            'customer_related_id.eq': relatedId,
            'pay_status.eq': PayStatus.Finished,
            groupFunc: 'sum(credit_warrant_fee_register.confirm_warrant_fee)',
          },
        })
        .then(res => {
          const data = res.data || []
          if (data.length) {
            this.finishedTotalFunds = +(data[0].p || 0)
          }
        })
        .catch(() => {
          this.finishedTotalFunds = 0
        })
    },
  },
}
</script>
<style lang="scss" scoped></style>
